package org.huoran.sakamichi.main.netty.webSocket;


import java.util.concurrent.ConcurrentHashMap;

public class ClientManager {
    private final ConcurrentHashMap<String, String> clientMap = new ConcurrentHashMap<>();

    private ClientManager() {}

    private static volatile ClientManager instance;

    public static ClientManager getInstance(){
        if(instance == null){
            synchronized (ClientManager.class){
                if(instance == null){
                    instance = new ClientManager();
                }
            }
        }
        return instance;
    }

    public String get(String name){
        return clientMap.get(name);
    }

    public String put(String name, String location){
        return putWithUnrepeatedName(name, location, 0);
    }

    public void remove(String location){
        clientMap.remove(location);
    }

    public boolean containsName(String name){
        return clientMap.containsValue(name);
    }

    public boolean containsLocation(String location){
        return clientMap.containsKey(location);
    }

    public String getNameByLocation(String location){
        return clientMap.get(location);
    }

    private String putWithUnrepeatedName(String name, String location, int index){
        String name_add = name;
        if(index > 0){
            name_add = name + index;
        }
        if(containsName(name_add)){
            index++;
            return putWithUnrepeatedName(name, location, index);
        }
        else{
            clientMap.put(location, name_add);
            return name_add;
        }
    }

}
